<script>
import { mapMutations, mapState } from "vuex";
// import GoEasy from './lib/goeasy-1.2.1.js';

export default {
  data() {
    return {
      innerAudioContext: null,
      innerAudioContext1: null,
      isOpen1: false,
      timer: null,

      alive: false,
      message: "",
      socketTask: null,
    };
  },
  globalData: {
    //全局挂载，若不需要支持nvue，也可以在main.js里挂在Vue.prototype,其他页面通过this.goEasy获取
    // goEasy: GoEasy.getInstance({
    // 	host:"hangzhou.goeasy.io",//应用所在的区域地址: 【hangzhou.goeasy.io |singapore.goeasy.io】
    //     appkey:'BC-b4d39782d7334752b58240ed062e958f',// common key,
    //     // true表示支持通知栏提醒，false则表示不需要通知栏提醒
    //     allowNotification:true //仅有效于app，小程序和H5将会被自动忽略
    // })
  },
  onLaunch: function () {
    /*console.log("App Launch");
		uni.setTabBarItem({
		    index: 0,
		    text: this.$lan('资产')
		});
		uni.setTabBarItem({
		    index: 1,
		    text: this.$lan('矿池')
		});
		uni.setTabBarItem({
		    index: 2,
		    text: this.$lan('社区')
		});
		uni.setTabBarItem({
		    index: 3,
		    text: this.$lan('商城')
		});
		uni.setTabBarItem({
		    index: 4,
		    text: this.$lan('我的')
		});*/

    // #ifdef H5
    //在页面加载时读取sessionStorage里的状态信息
    if (sessionStorage.getItem("store")) {
      this.$store.replaceState(
        Object.assign(
          {},
          this.$store.state,
          JSON.parse(sessionStorage.getItem("store"))
        )
      );
      sessionStorage.removeItem("store");
    }
    //在页面刷新时将vuex里的信息保存到sessionStorage里
    window.addEventListener("beforeunload", () => {
      sessionStorage.setItem("store", JSON.stringify(this.$store.state));
    });
    // #endif

    getApp().globalData.v = this;
    // #ifdef APP-PLUS
    plus.screen.lockOrientation("portrait-primary");
	
    // #endif
	
    // 	this.globalData.goEasy.connect({
    // 	// userId: userid,
    // 	onSuccess: function(){
    // 	// console.log("GoEasy connect successfully.")
    // 	},
    // 	onFailed: function(error){
    // 	},
    // 	onProgress: function(attempts){
    // 		// console.log("GoEasy is connecting", attempts);
    // 	}
    // });
  },
  onShow() {
    let _this = getApp().globalData.v;
    if (_this.isLogin) {
      //   const userinfo = _this.app.getUserInfo()
      // //   _this.reconect()
      // //    _this.globalData.goEasy.disconnect({
      // //       onSuccess: function(){
      // //           _this.globalData.goEasy.connect({
      // //               // userId: userid,
      // //               onSuccess: function(){
      // //                   _this.globalData.goEasy.subscribe({
      // //                         channel: userinfo.user_id,
      // //                         onMessage: function (message) {
      // // 							_this.stopAll()
      // //                             if (message.content == 1) {
      // //                               _this.showMSG()
      // //                             } else if (message.content == 2) {
      // //                               _this.showMSG1()
      // //                             }
      // //                         },
      // //                         onSuccess: function () {
      // //                         },
      // //                         onFailed: function (error) {
      // //                         }
      // //                     });
      // //               },
      // //               onFailed: function(error){
      // //               },
      // //               onProgress: function(attempts){
      // //               }
      // //           });
      // //       },
      // //       onFailed: function(error){
      // //         ;
      // //       }
      // //   });
    }
  },
  onHide: function () {},
  computed: {
    ...mapState(["isOpen", "isLogin", "defaultWallet"]),
  },

  mounted() {
    // this.innerAudioContext = uni.createInnerAudioContext()
    // this.innerAudioContext.autoplay = false;
    // this.innerAudioContext.src = './static/notice.mp3'
    // this.innerAudioContext1 = uni.createInnerAudioContext()
    // this.innerAudioContext1.autoplay = false;
    // this.innerAudioContext1.src = './static/notice1.mp3'
  },
  watch: {
    /*isLogin: function(n,o) {
      if (n) {
		let _this = this
		_this.initSocket()
		 const userid = this.app.getUserInfo().user_id
		 
         this.globalData.goEasy.subscribe({
            channel: userid,
            onMessage: function (message) {
			  _this.stopAll()
			  console.log(41324124)
              if (message.content == 1) {
                _this.showMSG()
              } else if (message.content == 2) {
                _this.showMSG1()
              }
                
            },
            onSuccess: function () {
                
            },
            onFailed: function (error) {
                
            }
        });
      }
    },*/
    defaultWallet: {
      deep: true, //深度监听设置为 true
      handler: function (newV, oldV) {
        if (newV && newV.address) {
          //		 this.getContractAddresses()
        }
      },
    },
    // isOpen: function (o, n) {
    // 	this.isOpisOpen1en = o;
    // 	if (o) {
    // 	//	this.initSocket();
    // 		this.app.tips('开始接单');
    // 	} else {
    // 	//	uni.closeSocket();
    // 		this.app.tips('停止接单');
    // 	}
    // },
  },
  methods: {
    ...mapMutations(["changeshowMsg", "changeshowMsg1", "changeSetOrder"]),
    
    showMSG1() {
      this.changeshowMsg1(true);

      try {
        this.changeSetOrder(true);
        setTimeout(() => {
          this.changeSetOrder(false);
        }, 15000);
      } catch (error) {}
      console.log(222222);
      this.innerAudioContext1.play();
    },
    stopAll() {
      try {
        this.innerAudioContext.stop(); // 新订单
        this.innerAudioContext1.stop(); // 超时订单
      } catch (error) {}
    },
    showMSG() {
      this.changeshowMsg(true);
      try {
        this.changeSetOrder(true);
        setTimeout(() => {
          this.changeSetOrder(false);
        }, 15000);
      } catch (error) {}
      this.innerAudioContext.play();
    },
    sendHeardBean() {
      // this.alive = false;
      const userinfo = this.app.getUserInfo();
      this.socketTask.send({
        data: JSON.stringify({ Cmd: "hb", id: userinfo.user_id }),
        success: (r) => {},
      });

      this.timer = setInterval(() => {
        this.alive = false;
        this.socketTask.send({
          data: JSON.stringify({ Cmd: "hb", id: userinfo.user_id }),
          success: (r) => {
            let timeror = setTimeout(() => {
              if (!this.alive) {
                this.reconect();
              }
              clearTimeout(timeror);
            }, 100000);
          },
        });
      }, 5000);
    },
    reconect() {
      clearInterval(this.timer);
      this.socketTask && this.socketTask.close();
      this.socketTask = null;
      this.initSocket();
    },
    open() {
      this.socketTask &&
        this.socketTask.onOpen((res) => {
          this.sendHeardBean();
          this.onMessage();
          this.error();
        });
    },
    error() {
      this.socketTask.onError((res) => {
        clearInterval(this.timer);
        this.socketTask.close();
        this.initSocket();
      });
    },
    onMessage() {
      const userinfo = this.app.getUserInfo();
      this.socketTask.onMessage((res) => {
        const da = JSON.parse(res.data);
        if (da.Cmd == "notice") {
          this.stopAll();
          if (da.data == 1) {
            this.showMSG();
          } else {
            this.showMSG1();
          }
        }
        if (da.Cmd == "hb") {
          this.alive = true;
          this.socketTask.send({
            data: JSON.stringify({ Cmd: "hb", id: userinfo.user_id }),
          });
        }
      });
    },
    initSocket() {
      const userinfo = this.app.getUserInfo();
      this.socketTask = uni.connectSocket({
        url: this.app.wsHost + `/id/${userinfo.user_id}`,
        header: {
          "content-type": "application/json",
        },
        success: (r) => {
          // this.open();
        },
      });
      this.socketTask && this.open();
    },
  },
};
</script>

<style lang="scss">

@import "@/static/font/iconfont.css";
page {
	background-color: #f6f6f6;
  box-sizing: border-box;
  overflow-y: auto;
}
/*每个页面公共css */
@import "./common/common.scss";

</style>
